package main;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import util.InputOutputStreamConnector;

import com.comp5900.interfaces.IFingerprint;
import com.comp5900.interfaces.IFingerprintGeneratorDetector;
import com.comp5900.interfaces.IFingerprintResult;


public class JarComparator implements IFingerprintGeneratorDetector {
	
	private String id;
	
	public JarComparator() {
		this.id = "ZOMG I'm an ID";
	}
	
	@Override
	public IFingerprint generateFingerprintFrom(String jarFilename) {
		
		// set up the IFingerprint
		IFingerprint fingerprint = new JarFingerprint();
		fingerprint.setJarFilename(jarFilename);
		
		// Compute the fingerprint
		
		JarFile fileToFingerprint = null;
		FingerprintGenerator gen = new FingerprintGenerator();
		
		// Open the jar file
		
		try {
			fileToFingerprint = new JarFile(jarFilename);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// Get all the entries in the JAR file
		Enumeration<JarEntry> fileEntries = fileToFingerprint.entries();
		while (fileEntries.hasMoreElements()) {
			
			// for each entry's InputStream and send it to a ByteArrayOutputStream via the IOStreamConnector
			JarEntry currentEntry = fileEntries.nextElement();
			InputOutputStreamConnector<InputStream, ByteArrayOutputStream> ioConnector = new InputOutputStreamConnector<InputStream, ByteArrayOutputStream>(null, null);
			try {
				ioConnector.setInputStream(fileToFingerprint.getInputStream(currentEntry));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ioConnector.setOutputStream(new ByteArrayOutputStream());
			try {
				ioConnector.go();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// Pass the collected bytes to our fingerprint generator
			gen.addSection(ioConnector.getOutputStream().toByteArray());	
		}
		
		// set the fingerprint data
		fingerprint.setEncoding(gen.getFingerprint());
		return fingerprint;
	}

	@Override
	public IFingerprintResult generateFingerprintResultFrom( IFingerprint fingerPrint, String jarFilename) {
		IFingerprintResult result = new JarCompareResult();
		return result;
	}

	@Override
	public String getId() {
		return this.id;
	}

}
